import axios from "axios"
import settle from "axios/lib/core/settle"
import buildURL from "axios/lib/helpers/buildURL"

//真机获取 解决app上adapter is not a function问题
axios.defaults.adapter = function(config) {
  return new Promise((resolve, reject) => {
	  if (baseUrl == '') {
		  const accountInfo = uni.getAccountInfoSync();
		  if (accountInfo) {
		  	baseUrl = accountInfo.miniProgram.envVersion == 'release' ? 'https://www.youpaish.com' : 'https://uat.youpaish.com';
		  } else {
			  baseUrl = 'https://www.youpaish.com'
		  }
	  }
	  console.log(baseUrl);
      uni.request({
          method: config.method.toUpperCase(),
          url: baseUrl + buildURL(config.url, config.params, config.paramsSerializer),
          header: config.headers,
          data: config.data,
          dataType: config.dataType,
          responseType: config.responseType,
          sslVerify: config.sslVerify,
          complete: function complete(response) {
              response = {
                  data: response.data,
                  status: response.statusCode,
                  errMsg: response.errMsg,
                  header: response.header,
                  config: config
              };

              settle(resolve, reject, response);
          }
      })
  })
}

let baseUrl = '';
// let baseUrl = 'http://192.168.0.40:4502';
// let baseUrl = 'https://uat.youpaish.com';
// let baseUrl = 'https://www.youpaish.com';
const instance = axios.create({
	baseURL: '',
    timeout: 10000,
});

instance.interceptors.request.use(
    (config) => {
        const token = uni.getStorageSync('token');
		if (token) {
			config.headers['token'] = token;
		}
        return config;
    },
    (error) => {
        console.log(error);
        return Promise.reject(error);
    }
);

instance.interceptors.response.use(
    (response) => {
        const res = response.data;
		// console.log('---response---', res)
        if (res.code === 0) {
            return res.data;
        } else {
            return Promise.reject({
                msg: res.msg || res.message,
                code: res.code
            });
        }
    },
    (error) => {
		// console.log(error);
        if (error && error.response && error.response.status) {
            if (error.response.status === 401) {
                localStorage.clear();
                window.location.reload();
                return Promise.reject({
                    msg: '登录过期',
                    code: error.response.status
                });
            } else {
                return Promise.reject({
                    msg: '系统错误',
                    code: error.response.status
                });
            }
        } else {
            return Promise.reject({
                msg: '系统超时',
                code: '500'
            });
        }
    }

);

export default instance;

